import qs from 'qs';
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import 'video-react/dist/video-react.css';
import VirtualizedSlider from '../../components/VirtualizedSlider';
import { useDirectory } from '../../context';
import { http } from '../../util';
import { ListItemType } from '../Home';

export const ImagePage = () => {
  const { search } = useLocation<Location>();
  const [listData, setListData] = useState<ListItemType[]>([]);
  const { setDirectory } = useDirectory();
  const { index, directory } = qs.parse(search.substring(1)) as any;
  useEffect(() => {
    setDirectory(directory.split('\\'));
    http('list', { data: { directory: directory } })
      .then(data => {
        if (data.message.toUpperCase() !== 'OK' || data.status !== 200) {
          throw new Error(data.message);
        }
        setListData(data.data.filter((item: ListItemType) => item.type === 'IMAGE'));
      });
  }, [directory, setDirectory]);
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [search]);

  return (
    <VirtualizedSlider
      directory={directory}
      list={listData}
      index={parseInt(index)}
    />
  );
};
